import {
  ElButton,
  ElDialog,
  ElInput,
  ElTable,
  ElTableColumn,
} from "element-plus";
import { defineComponent, createVNode, render, reactive } from "vue";
import deepCopy from "deep-copy";
const TableDialogComponent = defineComponent({
  props: { option: { type: Object } },
  setup(props, ctx) {
    const state = reactive({
      option: props.option,
      editData: [],
      isShow: false,
    });
    const show = (option) => {
      state.option = option;
      state.editData = deepCopy(option.data);
      state.isShow = true;
    };
    ctx.expose({ show });
    const add = () => {
      state.editData.push({});
    };
    const onDelete = (index) => {
      state.editData = state.editData.splice(index, index + 1);
    };
    const onConfirm = () => {
      state.option.onConfirm(state.editData);
      onCancel();
    };
    const onCancel = () => {
      state.isShow = false;
    };
    return () => {
      return (
        <ElDialog v-model={state.isShow} title={state.option.title}>
          {{
            default: () => (
              <div>
                <div>
                  <ElButton type="success" onClick={add} size="mini">
                    添加
                  </ElButton>
                </div>
                <ElTable border size="mini" data={state.editData} height={300}>
                  <ElTableColumn label="序号" align="center" type="index"></ElTableColumn>
                  {state.option.config.table.options.map((item, index) => {
                    return (
                      <ElTableColumn  align="center" label={item.label}>
                        {{
                          default: ({ row }) => (
                            <ElInput size="mini" v-model={row[item.field]}></ElInput>
                          ),
                        }}
                      </ElTableColumn>
                    );
                  })}
                  <ElTableColumn align="center" width={90} label="操作">
                    <ElButton
                      onClick={(index) => onDelete(index)}
                      size="mini"
                      type="danger"
                    >
                      删除
                    </ElButton>
                  </ElTableColumn>
                </ElTable>
              </div>
            ),
            footer: () => (
              <div>
                <ElButton onClick={onConfirm} size="mini" type="primary">
                  确定
                </ElButton>
                <ElButton size="mini" onClick={onCancel}>
                  取消
                </ElButton>
              </div>
            ),
          }}
        </ElDialog>
      );
    };
  },
});
let vm;
const $tableDialog = (option) => {
  if (!vm) {
    const el = document.createElement("div");
    vm = createVNode(TableDialogComponent, { option });
    document.body.appendChild((render(vm, el), el));
  }
  let { show } = vm.component.exposed;
  show(option);
};
export default $tableDialog;
